package com.xysd.express.activity.mine;

import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;

import com.bumptech.glide.Glide;
import com.google.gson.Gson;
import com.jph.takephoto.app.TakePhoto;
import com.jph.takephoto.app.TakePhotoImpl;
import com.jph.takephoto.compress.CompressConfig;
import com.jph.takephoto.model.CropOptions;
import com.jph.takephoto.model.InvokeParam;
import com.jph.takephoto.model.TContextWrap;
import com.jph.takephoto.model.TImage;
import com.jph.takephoto.model.TResult;
import com.jph.takephoto.model.TakePhotoOptions;
import com.jph.takephoto.permission.InvokeListener;
import com.jph.takephoto.permission.PermissionManager;
import com.jph.takephoto.permission.TakePhotoInvocationHandler;
import com.xysd.express.R;
import com.xysd.express.base.BaseActivity;
import com.xysd.express.bean.UploadImgObj;
import com.xysd.express.util.ActivityTaskManeger;
import com.xysd.express.util.JSONParser;
import com.xysd.express.util.LoadingDialogUtils;
import com.xysd.express.util.StringUtils;
import com.xysd.express.util.ToastUtil;
import com.xysd.express.util.http.HttpCallBack;
import com.xysd.express.util.http.HttpUtil;
import com.xysd.express.widget.dialog.BottomDialog;
import com.xysd.express.widget.dialog.Item;
import com.xysd.express.widget.dialog.OnItemClickListener;

import org.xutils.view.annotation.ContentView;
import org.xutils.view.annotation.ViewInject;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.util.ArrayList;

@ContentView(R.layout.activity_identification)
public class IdentificationActivity extends BaseActivity implements View.OnClickListener , TakePhoto.TakeResultListener, InvokeListener {
    @ViewInject(R.id.name_et)
    private EditText name_et;
    @ViewInject(R.id.idcard_et)
    private EditText idcard_et;
    @ViewInject(R.id.add_front_img)
    private ImageView add_front_img;
    @ViewInject(R.id.add_rear_img)
    private ImageView add_rear_img;
    @ViewInject(R.id.add_hands_img)
    private ImageView add_hands_img;
    @ViewInject(R.id.commit_btn)
    private Button commit_btn;

    private String name,idNum;
    private String frontUrl,rearUrl,handsUrl;

    @Override
    protected void init() {
        setTitleBar("实名认证");
        add_front_img.setOnClickListener(this);
        add_rear_img.setOnClickListener(this);
        add_hands_img.setOnClickListener(this);
        commit_btn.setOnClickListener(this);


    }

    @Override
    public void onClick(View v) {

        int width=add_front_img.getWidth();
        int height=add_front_img.getHeight();
        LinearLayout.LayoutParams params=new LinearLayout.LayoutParams(width,height);
        add_front_img.setLayoutParams(params);
        add_rear_img.setLayoutParams(params);
        add_hands_img.setLayoutParams(params);
        switch (v.getId()){
            case R.id.add_front_img:
                showPhotoDialog();
                break;
            case R.id.add_rear_img:
                showPhotoDialog();
                break;
            case R.id.add_hands_img:
                showPhotoDialog();
                break;
            case R.id.commit_btn:
                name=name_et.getText().toString();
                idNum=idcard_et.getText().toString();
                if (TextUtils.isEmpty(name)){
                    ToastUtil.show("姓名不能为空");
                    break;
                }
                if (!StringUtils.isIDCard(idNum)){
                    ToastUtil.show("请正确输入身份证号");
                    break;
                }
                upload();

                break;
        }
    }

    private void upload() {
        if (files.size()<3){
            ToastUtil.show("请正确上传所需图片");
            return;
        }
        LoadingDialogUtils.createLoadingDialog(mActivity).show();
        HttpUtil.uploadImg(files, new HttpCallBack() {
            @Override
            public void onSuccess(String result) {
                Log.i("上传图片",result);
                String code = JSONParser.getStringFromJsonString("Status",result);
                String msg = JSONParser.getStringFromJsonString("Msg",result);
                if ("0".equals(code)){
                    frontUrl= new Gson().fromJson(result, UploadImgObj.class).Data.get(0);
                    rearUrl= new Gson().fromJson(result, UploadImgObj.class).Data.get(1);
                    handsUrl= new Gson().fromJson(result, UploadImgObj.class).Data.get(2);
                    commit();
                }
                else {
                    ToastUtil.show(msg);
                    LoadingDialogUtils.closeLoadingDialog();
                }
            }

            @Override
            public void onFailure(String error) {
                Log.e("上传图片",error);
                LoadingDialogUtils.closeLoadingDialog();
            }
        });
    }

    private void commit() {
        HttpUtil.identification(name, idNum, frontUrl, rearUrl, handsUrl, new HttpCallBack() {
            @Override
            public void onSuccess(String result) {
                LoadingDialogUtils.closeLoadingDialog();
                Log.i("认证",result);
                String code = JSONParser.getStringFromJsonString("Status",result);
                String msg = JSONParser.getStringFromJsonString("Msg",result);
                if ("0".equals(code)){
                    ActivityTaskManeger.getInstance().closeActivity(mActivity);
                }
                ToastUtil.show(msg);
            }

            @Override
            public void onFailure(String error) {
                LoadingDialogUtils.closeLoadingDialog();
                Log.e("认证",error);
            }
        });
    }


    /**
     * ************************************* 以下尝试使用takephoto ************************************************
     */

    @Override
    public void onSaveInstanceState(Bundle outState) {
        getTakePhoto().onSaveInstanceState(outState);
        super.onSaveInstanceState(outState);
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        getTakePhoto().onActivityResult(requestCode, resultCode, data);
        super.onActivityResult(requestCode, resultCode, data);
    }

    private TakePhoto takePhoto;
    private InvokeParam invokeParam;


    //文件转成字节数组
    public static byte[] readStream(String imagepath) {
        FileInputStream fs = null;
        ByteArrayOutputStream outStream = null;
        try {
            fs = new FileInputStream(imagepath);
            outStream = new ByteArrayOutputStream();
            byte[] buffer = new byte[1024];
            int len = 0;
            while (-1 != (len = fs.read(buffer))) {
                outStream.write(buffer, 0, len);
            }
            outStream.close();
            fs.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return outStream.toByteArray();
    }


    @Override
    public void takeSuccess(TResult result) {
        showImg(result.getImage());
    }

    @Override
    public void takeFail(TResult result, String msg) {
        Log.i("takephoto", "takeFail:" + msg);
    }

    @Override
    public void takeCancel() {
        Log.i("takephoto", getResources().getString(R.string.msg_operation_canceled));
    }

    private File imgFile;
    private ArrayList<String> path = new ArrayList<>();
    private ArrayList<File> files = new ArrayList<>();
    private ArrayList<byte[]> bytes = new ArrayList<>();


    private void showImg(TImage image) {
        imgFile = new File(image.getCompressPath());
        files.add(imgFile);
        path.add(image.getCompressPath());
        bytes.add(readStream(image.getCompressPath()));
        if (files.size()==1){
            Glide.with(this).load(image.getCompressPath()).into(add_front_img);
            add_front_img.setClickable(false);
        }
        if (files.size()==2){
            Glide.with(this).load(image.getCompressPath()).into(add_rear_img);
            add_rear_img.setClickable(false);
        }
        if (files.size()==3){
            Glide.with(this).load(image.getCompressPath()).into(add_hands_img);
            add_hands_img.setClickable(false);
        }

    }

    BottomDialog dialog;

    public void showPhotoDialog() {
        dialog = new BottomDialog(mActivity)
//                .title(R.string.title_item)             //设置标题
//                .layout(BottomDialogInandOut.GRID)              //设置内容layout,默认为线性(LinearLayout)
                .orientation(BottomDialog.VERTICAL)     //设置滑动方向,默认为横向
                .inflateMenu(R.menu.menu_photo, new OnItemClickListener() {//传人菜单内容和监听
                    @Override
                    public void click(Item item) {
                        switch (item.getId()) {
                            case R.id.camera:
                                fromCamera();
                                dialog.cancle();
                                break;

                            case R.id.photo:
                                formPhoto();
                                dialog.cancle();
                                break;
                        }
                    }
                });

        dialog.show();
    }

    private void formPhoto() {
        TakePhoto takePhoto = getTakePhoto();
        File file = new File(getExternalFilesDir(null), "/img/" + System.currentTimeMillis() + ".jpg");
        if (!file.getParentFile().exists()) file.getParentFile().mkdirs();
        Uri imageUri = Uri.fromFile(file);
        configCompress(takePhoto);
        configTakePhotoOption(takePhoto);
//        takePhoto.onPickFromGalleryWithCrop(imageUri, getCropOptions());
        takePhoto.onPickFromGallery();
    }

    private void fromCamera() {
        TakePhoto takePhoto = getTakePhoto();
        File file = new File(getExternalFilesDir(null), "/img/" + System.currentTimeMillis() + ".jpg");
        if (!file.getParentFile().exists()) file.getParentFile().mkdirs();
        Uri imageUri = Uri.fromFile(file);
        configCompress(takePhoto);
        configTakePhotoOption(takePhoto);
        takePhoto.onPickFromCapture(imageUri);
//        takePhoto.onPickFromCaptureWithCrop(imageUri, getCropOptions());
    }

    private void configTakePhotoOption(TakePhoto takePhoto) {
        TakePhotoOptions.Builder builder = new TakePhotoOptions.Builder();
        builder.setWithOwnGallery(true);
        builder.setCorrectImage(true);
        takePhoto.setTakePhotoOptions(builder.create());
    }

    private void configCompress(TakePhoto takePhoto) {
        int maxSize = 102400;
        int width = 800;
        int height = 800;
        boolean showProgressBar = false;//不显示压缩进度条
        boolean enableRawFile = true;//压缩后保存原图
        CompressConfig config;
        config = new CompressConfig.Builder()
                .setMaxSize(maxSize)
                .setMaxPixel(width >= height ? width : height)
                .enableReserveRaw(enableRawFile)
                .create();
        takePhoto.onEnableCompress(config, showProgressBar);
    }

    private CropOptions getCropOptions() {
        int height = 800;
        int width = 800;
        boolean withWonCrop = true;
        CropOptions.Builder builder = new CropOptions.Builder();
        builder.setOutputX(width).setOutputY(height);
        builder.setWithOwnCrop(withWonCrop);
        return builder.create();
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        //以下代码为处理Android6.0、7.0动态权限所需
        PermissionManager.TPermissionType type = PermissionManager.onRequestPermissionsResult(requestCode, permissions, grantResults);
        PermissionManager.handlePermissionsResult(this, type, invokeParam, this);
    }

    @Override
    public PermissionManager.TPermissionType invoke(InvokeParam invokeParam) {
        PermissionManager.TPermissionType type = PermissionManager.checkPermission(TContextWrap.of(this), invokeParam.getMethod());
        if (PermissionManager.TPermissionType.WAIT.equals(type)) {
            this.invokeParam = invokeParam;
        }
        return type;
    }

    /**
     * 获取TakePhoto实例
     *
     * @return
     */
    public TakePhoto getTakePhoto() {
        if (takePhoto == null) {
            takePhoto = (TakePhoto) TakePhotoInvocationHandler.of(this).bind(new TakePhotoImpl(this, this));
        }
        return takePhoto;
    }
}
